// pages/home/index.js

const app = getApp() // 当前的页面的实例
// 需求，获取到当前页面的路由
console.log('app:', app)

const fetchData = ({ page = 1, size = 5 }) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const list = [{
        "id": 1,
        "goods": "goods-num1",
        "num": 1,
        "price": "10.00",
        "desc": "goods-商品描述"
      },
      {
        "id": 2,
        "goods": "goods-num1",
        "num": 1,
        "price": "10.00",
        "desc": "goods-商品描述"
      },
      {
        "id": 3,
        "goods": "goods-num1",
        "num": 1,
        "price": "10.00",
        "desc": "goods-商品描述"
      },
      {
        "id": 4,
        "goods": "goods-num1",
        "num": 1,
        "price": "10.00",
        "desc": "goods-商品描述"
      },
      {
        "id": 5,
        "goods": "goods-num1",
        "num": 1,
        "price": "10.00",
        "desc": "goods-商品描述"
      }]
      resolve(list.slice((page - 1) * size, page * size))
    }, 500)
  })
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    routerPath: '',
    disabled: true,
    isSearchClick: true,
    list: [],
    options: {
      page: 1,
      size: 5
    }
  },

  // 请求数据

  async fetchList() {
    const response = await fetchData({ ...this.data.options })
    console.log('response:', response)
    // response.forEach(item => {
    // })
    // es6:
    for (let item of response) {
      item.checked = false
    }
    console.log('response:', response)
    this.setData({ list: response })
  },

  // 搜索功能
  searchChange(e) {
    console.log('e:', e.detail.value)
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    const pages = getCurrentPages();
    const route = pages.pop().route
    console.log('home:', route)
    this.setData({
      routerPath: route
    })
    // 初始化请求数据
    this.fetchList({})
  },

  // tabBar - 如何做导航守卫？
  onClick() {
    // 导航守卫
    const token = wx.getStorageSync('token')
    if (token) {
      wx.navigateTo({
        url: '/pages/cart/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/center/index',
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})